<template>
  <div class="app-container">
    <el-dialog :title="title" :visible.sync="dialogFormVisible" width="70%">
      <el-form ref="dialogForm" :model="form" :inline="true" :rules="rules" class="demo-ruleForm">
        <el-row :gutter="10">
          <el-col :span="11">
            <div class="grid-content bg-purple">
              <el-form-item label="登录账号" :label-width="formLabelWidth" prop="account">
                <el-input v-model="form.account" autocomplete="off"></el-input>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="11">
            <div class="grid-content bg-purple">
              <el-form-item label="手机号码" :label-width="formLabelWidth" prop="mobile">
                <el-input v-model="form.mobile" autocomplete="off" ></el-input>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="11">
            <div class="grid-content bg-purple">
              <el-form-item label="用户昵称" :label-width="formLabelWidth" prop="name">
                <el-input v-model="form.name" autocomplete="off"></el-input>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="11">
            <div class="grid-content bg-purple">
              <el-form-item label="真实姓名" :label-width="formLabelWidth" prop="realName">
                <el-input v-model="form.realName" autocomplete="off"></el-input>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="11">
            <div class="grid-content bg-purple">
              <el-form-item label="用户生日" :label-width="formLabelWidth">
                <el-date-picker v-model="form.birthdays" type="date" placeholder="请输入用户生日" style="width: 100%;" />
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="11">
            <div class="grid-content bg-purple">
                <el-form-item label="用户性别" :label-width="formLabelWidth">
                  <el-radio-group v-model="form.sex">
                    <el-radio label="1">男</el-radio>
                    <el-radio label="0">女</el-radio>
                  </el-radio-group>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="11">
            <div class="grid-content bg-purple">
              <el-form-item label="所属部门" :label-width="formLabelWidth">
                <div class="block">
                  <el-cascader
                    placeholder="请选择所属部门"
                    v-model="treeDep.mainDep"
                    :options="treeDep.mainDepData"
                    :change-on-select=true
                    :props="{ expandTrigger: 'click', value:'id', label: 'name', children: 'children'}"></el-cascader>
                </div>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="11">
            <div class="grid-content bg-purple">
              <el-form-item label="入职日期" :label-width="formLabelWidth">
                <el-date-picker
                  v-model="form.joinDate"
                  align="right"
                  type="date"
                  placeholder="选择日期"
                  :picker-options="pickerOptions">
                </el-date-picker>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="FormSub('dialogForm')">确 定</el-button>
      </div>
    </el-dialog>
    <el-container>
      <el-aside width="200px">
        <el-header style="font-size: 12px">
        <el-input v-model="filterText" placeholder="输入关键字进行过滤"/>
        </el-header>
        <el-main>
          <el-tree
            ref="tree"
            node-key="id"
            default-expand-all
            :props="treeDep.props"
            :data="treeData"
            class="filter-tree"
            :filter-node-method="filterNode"
            @node-click="nodeClick"
          />
        </el-main>
      </el-aside>
      <el-container>
        <el-header style="font-size: 12px">
          <el-form :inline="true" :model="seachForm" class="demo-form-inline" ref="seachForm">
            <el-form-item label="部门名称">
              <el-input v-model="seachForm.user" placeholder="请输入部门名称"></el-input>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="seachForm.region" placeholder="请选择">
                <el-option label="正常" value="0"></el-option>
                <el-option label="停用" value="1"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="seachSubmit('seachForm')">查询</el-button>
              <el-button @click="seachResetForm('seachForm')">重置</el-button>
            </el-form-item>
            <el-form-item>

            </el-form-item>
          </el-form>
        </el-header>
        <el-main>
          <el-button-group style="margin: 0px 0px 10px 0px; text-align: right">
            <el-button type="primary" icon="el-icon-plus" @click="dialogForm(1)">添加</el-button>
            <el-button type="primary" icon="el-icon-edit" @click="dialogForm(2)">修改</el-button>
            <el-button type="primary" icon="el-icon-delete" @click="dialogDelete()">删除</el-button>
          </el-button-group>
          <el-table
            :columns="columns"
            ref="singleTable"
            v-loading="listLoading"
            row-key="id"
            :height="height"
            :data="list"
            @row-click='rowClick'
            highlight-current-row
            element-loading-text="Loading"
            border
            fit
            default-expand-all
            :tree-props="{children: 'children'}">
            <el-table-column v-for="(column, key) in columns"
                             :prop="column.prop"
                             :label="column.label"
                             :width="column.width"
                             :fixed="column.fixed"
                             :formatter="column.formatter">
            </el-table-column>
            <el-table-column
              prop="isValid"
              label="状态"
              width="100">
              <template slot-scope="scope">
                <el-tag
                  :type="scope.row.isValid === '0' ? 'primary' : 'success'"
                  disable-transitions>{{scope.row.isValid === '0'?'可用':'禁用'}}</el-tag>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            background
            :layout="layout"
            :total="total"
            :page-sizes="pageSizes"
            :page-size="pageSize"
            @size-change="sizeChange"
            @current-change="currentChange"
          />
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>
<script>
import { parseTime } from '@/utils'
export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'success',
        0: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      columns: [],
      height: 200,
      winHeight: 200,
      title: '',
      treeDep: {
        treeDep: [],
        mainDepData: [],
        subDepData: [],
        mainDep: [],
        subDep: [],
        props: {
          id: 'id',
          label: 'name',
          children: 'children'
        }
      },
      treeData: [],
      dialogFormVisible: false,
      layout: 'sizes, prev, pager, next, jumper, ->, total',
      pageSizes: [10, 20, 30, 40, 50, 100],
      pageSize: 10,
      parent: 0,
      total: 0,
      currentPage: 1,
      filterText: '',
      list: [],
      listLoading: true,
      formLabelWidth: '120px',
      row: [],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        },
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      },
      seachForm: {
        region: '',
        user: ''
      },
      form: {
        id: '',
        account: '',
        addOrup: 1,
        name: '',
        realName: '',
        birthdays: '',
        sex: '1',
        mobile: '',
        dep: '',
        joinDate: ''
      },
      rules: {
        account: [
            { required: true, message: '请输入登录账号', trigger: 'blur' },
            { min: 6, max: 6, message: '长度在 6 到 6 个字符', trigger: 'blur' }
        ],
        realName: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { min: 11, max: 11, message: '长度在 11 到 11 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created: function() {
    this.height = (window.innerHeight > 300 ? window.innerHeight - 230 : 100)
    this.getColumns()
    this.getMovie()
    this.superDepAjax()
  },
  mounted() {
    // 挂载浏览器高度获取方法
    const that = this
    window.onresize = () => {
      return (() => {
        that.winHeight = window.innerHeight
      })()
    }
    // this.$refs.nav.style.height = this.winHeight + 'px'
  },
  watch: {
    // 监控浏览器高度变化
    winHeight(val) {
      this.winHeight = val
      this.height = (this.winHeight > 300 ? this.winHeight - 230 : 100)
    }
  },
  methods: {
    state(row, column) {
      return row.val === 0 ? '<el-tag type="success">可用</el-tag>' : '<el-tag type="success">禁用</el-tag>'
    },
    getColumns() {
      const self = this
      this.$http.get('/dev-api/columns/table/by/YHGL')
        .then(res => {
          self.columns = res.data.data
          self.getList(self.currentPage, self.pageSize, this.parent)
        })
    },
    dialogDelete() {
      if (this.row.length <= 0) {
        alert('请先选择要删除的用户!')
        return
      }
      const self = this
      this.$confirm('此操作将删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const that = this
        this.$http.get('/dev-api/role/del/' + this.row.id)
          .then(res => {
            that.$message({
              type: res.data.code === 20000 ? 'success' : 'info',
              message: res.data.code === 20000 ? '删除成功！' : '删除失败！'
            })
            self.getList()
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    dialogForm(val) {
      this.form.id = ''
      this.form.realName = ''
      this.form.birthdays = ''
      this.form.mobile = ''
      this.form.name = ''
      this.form.account = ''
      if (val === 1) {
        this.title = '添加用户'
        this.form.sort = 1
        this.form.addOrup = 1
      } else {
        if (this.row.length <= 0) {
          alert('请先选择要修改的用户!')
          return
        }
        this.form.id = this.row.id
        this.form.account = this.row.account
        this.form.realName = this.row.realName
        this.form.birthdays = this.row.birthday
        this.form.mobile = this.row.userAuthLocal.mobile
        this.form.name = this.row.name
        this.form = this.row
        this.form.mobile = this.row.mobile
        this.title = '修改用户'
        this.form.addOrup = 2
      }
      this.dialogFormVisible = true
    },
    superDepAjax() {
      const that = this
      this.$http.get('/dev-api/dep/treeDep')
        .then(res => {
          for (var i = 0; i < res.data.data.length; i++) {
            if (res.data.data[i].children.length <= 0) {
              delete res.data.data[i].children
            } else {
              for (var a = 0; a < res.data.data[i]['children'].length; a++) {
                if (res.data.data[i]['children'][a].children.length <= 0) {
                  delete res.data.data[i]['children'][a].children
                }
              }
            }
          }
          that.treeDep.mainDepData = res.data.data
          that.treeDep.subDepData = res.data.data
        })
    },
    FormSub(formName) {
      this.form.mainDep = this.treeDep.mainDep[0]
      this.form.subDep = this.treeDep.subDep[0]
      const self = this
      if (this.form.addOrup === 1) {
        this.$refs[formName].validate((valid) => {
          // this.form.superMod = this.value[this.value.length - 1]
          this.$http.post('/dev-api/user/save', this.form)
            .then(res => {
              this.dialogFormVisible = false
              self.$message({
                type: res.data.code === 20000 ? 'success' : 'info',
                message: res.data.code === 20000 ? '保存成功！' : '保存失败！'
              })
              self.getList(self.currentPage, self.pageSize)
            })
        })
      } else {
        this.$refs[formName].validate((valid) => {
          this.$http.post('/dev-api/user/update', this.form)
            .then(res => {
              console.log(res.data.code)
              this.dialogFormVisible = false
              self.$message({
                type: res.data.code === 20000 ? 'success' : 'info',
                message: res.data.code === 20000 ? '修改成功！' : '修改失败！'
              })
              self.getList()
              this.dialogFormVisible = false
            })
        })
      }
    },
    seachSubmit(formName) {
      this.$refs[formName].resetFields()
    },
    seachResetForm(formName) {
      this.$refs[formName].resetFields()
    },
    getList: function() {
      var self = this
      this.$http.get('/dev-api/user/list?pageIndex=' + this.currentPage + '&pageSize=' + this.pageSize + '&depId=' + this.parent)
        .then(res => {
          self.list.pop()
          self.total = res.data.total
          self.list = res.data.data
          for (let i = 0; i < self.list.length; i++) {
            self.list[i].createTime = parseTime(self.list[i].createTime)
            self.list[i].modifyTime = parseTime(self.list[i].modifyTime)
            self.list[i].birthday = parseTime(self.list[i].birthday, '{y}-{m}-{d}')
          }
          self.listLoading = false
        })
    },
    currentChange(val) {
      this.currentPage = val
      this.getList()
    },
    sizeChange(val) {
      this.pageSize = val
      this.getList()
    },
    rowClick(row, column, event) {
      this.row = row
    },
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    getMovie: function() {
      var self = this
      this.$http.get('/dev-api/dep/treeDep')
        .then(res => {
          self.treeData.pop()
          self.treeData = res.data.data
        })
    },
    nodeClick: function(row) {
      this.parent = row.id
      this.getList()
    }
  }
}
</script>
